<?php
/**
* @author moufer<moufer@163.com>
* @copyright modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');

class MessageModel {

    function read($uid, $pmid) {
        $result = uc_pm_view($uid, $pmid);
        if(!$result) return;
        $msg['pmid'] = $result[0]['pmid']; 
        $msg['subject'] = $result[0]['subject']; 
        $msg['subject_enc'] = rawurlencode($result[0]['subject']); 
        $msg['content'] = $result[0]['message'];
        $msg['new'] = $result[0]['new'];
        $msg['recvuid'] = $result[0]['msgtoid'];
        $msg['senduid'] = $result[0]['msgfromid'];
        return $msg;
    }

    function delete($uid, $folder, $ids) {
        return uc_pm_delete($uid, $folder, $ids);
    }

    function send($senduid, $recvuid, $subject, $message, $isusername = false) {
        return uc_pm_send($senduid, $recvuid, $subject, $message, 1, 0, $isusername);
    }

    function getMessagesTotal($uid, $folder) {
        $result = uc_pm_list($uid,0,0,$folder,'');
        return $result['count'];
    }

    function & getMessages($uid, $folder, $limit) {
        $data = $result = array();
        preg_match("/^([0-9]+),\s+([0-9]+)$/",$limit,$match);
        $result = uc_pm_list($uid,$match[1],$match[2],$folder,'');
        if(empty($result['count'])) {
            $result = false;
        } else {
            foreach($result['data'] as $key=>$val) {
                $data[$key] = MessageModel::_convertMessageData($val,$folder);
            }
        }
        return $data;
    }

    function & getNewMessages($uid) {
        list($result,) = uc_pm_list($uid,1,50,$folder,'newpm',1);
        if(empty($result)) {
            $result = false;
        } else {
            foreach($result as $key=>$val) {
                $result[$key] = MessageModel::_convertMessageData($val,'inbox');
            }
        }
        return $result;
    }

    function & _convertMessageData(& $val,$folder) {
        global $db, $dbpre;
        $result = array();
        $result['pmid'] = $val['pmid'];
        $result['subject'] = $val['subject'];
        $result['new'] = $val['new'];
        $result['posttime'] = $val['dateline'];
        $result['content'] = $val['message'];
        if($folder=='inbox') {
            $result['uid'] = $val['msgfromid'];
            $result['username'] = $val['msgfrom'];
        } else {
            $result['uid'] = $val['msgtoid'];
            $result['username'] = $db->get_value("SELECT username FROM {$dbpre}members WHERE uid='{$val['msgtoid']}'");
        }
        return $result;
    }
}
?>
